package com.example.he.p0308_keytouch;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;

/**
 * 该类用于演示OnTouchEvent的使用
 *
 */
public class KeyTouchActivity extends AppCompatActivity {
    TouchView touchView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        touchView = new TouchView(this);    // 初始化自定义的View
        setContentView(touchView);   // 设置当前显示的用户界面
    }
    @Override
    public boolean onTouchEvent(MotionEvent event) { // 重写的onTouchEvent回调方法
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN://手指按下
                touchView.x = (int) event.getX();  // 改变x坐标
                touchView.y = (int) event.getY() - 270;  // 改变y坐标
                touchView.postInvalidate();   // 重绘
                break;
            case MotionEvent.ACTION_MOVE: //手指移动
                touchView.x = (int) event.getX();          // 改变x坐标
                touchView.y = (int) event.getY() - 270;   // 改变y坐标
                touchView.postInvalidate();    // 重绘
                break;
            case MotionEvent.ACTION_UP://手指抬起
                touchView.x = -100;    // 改变x坐标
                touchView.y = -100;    // 改变y坐标
                touchView.postInvalidate();  // 重绘
                break;
        }
        return super.onTouchEvent(event);
    }

    //定义新类
    class TouchView extends View {
        Paint paint;    // 画笔
        int x =300;     // x坐标
        int y = 300;    // y坐标
        int width = 100;    // 矩形的宽度

        public TouchView(Context context) {
            super(context);
            paint = new Paint();   // 初始化画笔
            paint.setColor(Color.BLUE);
        }

        //重载绘制方法
        @Override
        protected void onDraw(Canvas canvas) {
            canvas.drawColor(Color.CYAN);     // 绘制背景色
            canvas.drawRect(x - width/2, y - width/2 , x + width/2, y + width/2, paint);   // 绘制矩形
            super.onDraw(canvas);
        }
    }
}
